package com.studysystem.controller;

import com.studysystem.entity.CourseProgress;
import com.studysystem.entity.User;
import com.studysystem.repository.CourseProgressRepository;
import com.studysystem.repository.CourseRepository;
import com.studysystem.repository.UserRepository;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/user")
public class UserController {
    private final UserRepository userRepository;
    private final CourseProgressRepository courseProgressRepository;
    private final CourseRepository courseRepository;

    public UserController(UserRepository userRepository, CourseProgressRepository courseProgressRepository, CourseRepository courseRepository) {
        this.userRepository = userRepository;
        this.courseProgressRepository = courseProgressRepository;
        this.courseRepository = courseRepository;
    }

    @GetMapping("/me")
    public User getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) {
        Optional<User> user = userRepository.findByUsername(userDetails.getUsername());
        return user.orElse(null);
    }

    @GetMapping("/progress")
    public List<CourseProgress> getUserProgress(@AuthenticationPrincipal UserDetails userDetails) {
        Optional<User> user = userRepository.findByUsername(userDetails.getUsername());
        return user.map(value -> courseProgressRepository.findByUserId(value.getId())).orElse(null);
    }

    @GetMapping("/courses")
    public Object getUserCourses(@AuthenticationPrincipal UserDetails userDetails) {
        Optional<User> user = userRepository.findByUsername(userDetails.getUsername());
        if (user.isPresent()) {
            return courseProgressRepository.findByUserId(user.get().getId())
                    .stream()
                    .map(CourseProgress::getCourse)
                    .distinct()
                    .toArray();
        }
        return null;
    }
} 